#include <stdio.h>
#include <comedilib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <getopt.h>
#include <ctype.h>

#include <iostream>

comedi_t *device;


int main(int argc, char **argv) {
    std::cout << "Hello, Zsoci!" << std::endl;

    int i, j, k;
    lsampl_t data;
    int ch;
    int ret;
    int subdevice;
    int stype;
    char filename[]="/dev/comedi0";

//     if (argc!=3) {
//         fprintf(stderr,"%s <chan> <value>\n",argv[0]);
//         exit(-1);
//     }

    device = comedi_open(filename);
    if (!device) {
        comedi_perror(filename);
        exit(-1);
    }
    else
        std::cout << "Opened device!" << std::endl;


//ch = atoi(argv[1]);
//data = atoi(argv[2]);

// SUBDEV_AD             0
// SUBDEV_DA             1
// SUBDEV_DIO            2
// SUBDEV_COUNTER        3
// SUBDEV_PWM            4

    subdevice = 2;
    ch = 0 ;

    //    data = 1 ;

    
    stype = comedi_get_subdevice_type(device, subdevice);
    if (stype != COMEDI_SUBD_DIO) {
        printf("%d is not a digital I/O subdevice\n",subdevice);
        exit(-1);
    }
    else
        std::cout << "Obtained subdevice" << std::endl;

    ret = comedi_dio_config(device,subdevice,ch,COMEDI_OUTPUT);
    if (ret < 0) {
        comedi_perror(filename);
        exit(-1);
    }
    else
        std::cout << "Configured channel as output" << std::endl;

    for (i=0; i<10; i++) {
        ret = comedi_dio_write(device,subdevice,ch,0);
        if (ret < 0) {
            comedi_perror(filename);
            exit(-1);
        }
        else
            std::cout << "Wrote 0 to device" << std::endl;

	usleep(10000L);
	
        ret = comedi_dio_write(device,subdevice,ch,1);
        if (ret < 0) {
            comedi_perror(filename);
            exit(-1);
        }
        else
            std::cout << "Wrote 1 to device" << std::endl;
	
	usleep(190000L);
    }

    return 0;
}
